package com.yun.util.yun.leetCode.simple;
/**
 * 整数反转
 */
public class Inversion {

    public int reverse(int x) {
        if (x==0){
            return 0;
        }
        int symbol;
        String s = String.valueOf(x);
        char[] chars = s.toCharArray();
        if (chars[0]=='-'){
            char[] chars1 = this.delete(chars);
            try {
                symbol = Integer.parseInt("-"+this.symbolNo(chars1));
            }catch (NumberFormatException e){
                return 0;
            }
        } else {
            try {
                symbol = Integer.parseInt(this.symbolNo(chars));
            }catch (NumberFormatException e){
                return 0;
            }
        }
        return symbol;
    }

    private String symbolNo(char[] chars) {
        int[] ints = new int[chars.length];
        for (int i = 0; i < chars.length; i++) {
            ints[i] = chars[i]-48;
        }
        if (ints.length % 2 == 0){
            int j = ints.length / 2-1;
            for (int i = 0; i < ints.length; i++) {
                if (i>j){
                   break;
                }
                this.swap(ints,i,ints.length-1-i);
            }
        }else {
            int j = ints.length-1;
            j = j/2;
            for (int i = 0; i < ints.length; i++) {
                if (i == j){
                    break;
                }
                this.swap(ints,i,ints.length-1-i);
            }
        }
        StringBuilder builder = new StringBuilder();
        if (ints[0] != 0) {
            builder.append(ints[0]);
            for (int i = 1; i < ints.length; i++) {
                builder.append(ints[i]);
            }
        }else {
            builder.append(ints[1]);
            for (int i = 2; i < ints.length; i++) {
                builder.append(ints[i]);
            }
        }
        return String.valueOf(builder);
    }

    private char[] delete(char[] chars) {
        char[] chars1 = new char[chars.length-1];
        if (chars.length - 1 >= 0) System.arraycopy(chars, 1, chars1, 0, chars.length - 1);
        return chars1;
    }

    private void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }


    public static void main(String[] args) {
        int a = 654;
        Inversion inversion = new Inversion();
        int reverse = inversion.reverse(a);
        System.out.println(reverse);
    }
}
